﻿using RpcCentral.Common;
using RpcCentral.DAL;
using RpcCentral.Model;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;

namespace RpcCentral.Collect.Controller
{
    public class RpcVerController : DataSyncClass
    {
        private readonly long _RpcMerId;
        private readonly long _VerNum;
        private readonly long _SystemTypeId;
        private long _VerId;
        private bool _IsEnable = false;
        private Dictionary<long, VerRoute> _VerRoute;

        public RpcVerController (long rpcMerId, long sysTypeId, long ver)
        {
            this._RpcMerId = rpcMerId;
            this._VerNum = ver;
            this._SystemTypeId = sysTypeId;
        }
        protected override void SyncData ()
        {
            using (IocScope scope = UnityHelper.CreateScore())
            {
                this._VerId = scope.Resolve<IServiceVerConfigDAL>().GetVerId(this._VerNum, this._SystemTypeId, this._RpcMerId);
                if (this._VerId == 0)
                {
                    this._IsEnable = false;
                    return;
                }
                VerRoute[] routes = scope.Resolve<IServiceVerRouteDAL>().GetVerRoute(this._VerId);
                this._VerRoute = routes.ToDictionary(a => a.SystemTypeId, a => a);
                this._IsEnable = true;
            }
        }


        public ServerConfig[] Filters (long sysTypeId, ServerConfig[] servers)
        {
            if (!this._IsEnable || servers == null)
            {
                return servers;
            }
            else if (!this._VerRoute.TryGetValue(sysTypeId, out VerRoute route))
            {
                return servers;
            }
            else
            {
                return servers.FindAll(a => route.IsValid(a.VerNum));
            }
        }
    }
}
